from sqlalchemy.orm import Session
from sqlalchemy import and_
import json
from typing import List
from app.entity import SysMenu
from app.schema import MenuData
from utils.tree import TreeUtil

class MenuModel:
    """
    菜单管理模块数据库操作层
    """

    @classmethod
    def get_list(cls, db: Session, where):
        if where.get('menu_name', None)!=None:
            rows  = db.query(SysMenu).filter(SysMenu.menu_name==where['menu_name']).order_by(SysMenu.parent_id.asc(), SysMenu.order_num.asc()).all()
            return rows
        else:
            rows  = db.query(SysMenu).order_by(SysMenu.parent_id).all()
            rows = [ v.__dict__ for v in rows ]
            return TreeUtil.build_tree_nodes(rows, 'menu_id', 'parent_id')
    
    @classmethod
    def get_tree(cls, db: Session):
        rows  = db.query(SysMenu).filter(and_(SysMenu.menu_type!='F', SysMenu.visible=='0', SysMenu.status=='0')).order_by(SysMenu.parent_id.asc(), SysMenu.order_num.asc()).all()
        lists = []
        
        for v in rows:
            one = {
                'id': v.menu_id,
                'pid': v.parent_id,
                'name': v.menu_name,
                'path': v.path,
                'type': v.menu_type,
                'component': v.component
            }
            lists.append(one)
        return TreeUtil.build_tree_nodes(lists)
        
    @classmethod
    def get_trees(cls, db: Session):
        rows  = db.query(SysMenu).filter(SysMenu.menu_type!='F').order_by(SysMenu.parent_id.asc(), SysMenu.order_num.asc()).all()
        lists = []
        
        for v in rows:
            one = {
                'id': v.menu_id,
                'pid': v.parent_id,
                'name': v.menu_name,
                'path': v.path,
                'type': v.menu_type,
                'component': v.component
            }
            lists.append(one)
        return TreeUtil.build_tree_nodes(lists)
    
    @classmethod
    def insert(cls, db: Session, data: MenuData):
        print(data.dict())
        return True
        db_post = SysMenu(**data.dict())
        db.add(db_post)
        db.commit()
        return True
    

    @classmethod
    def edit(cls, db: Session, post: dict):
        db.query(SysMenu).filter(SysMenu.menu_id == post.get('menu_id')).update(post)
        db.commit()

    @classmethod
    def delete(cls, db: Session, ids: List[int]):
        db.query(SysMenu).filter(SysMenu.menu_id.in_(ids)).delete()
        db.commit()

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(SysMenu).filter(SysMenu.menu_id==id).first()